package com.nageoffer.aicloud.config;

import com.nageoffer.aicloud.common.bi.user.LoginAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring securiry 配置类
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecuriryConfiguration {
    private final LoginAuthenticationFilter loginAuthenticationFilter;

    /**
     * 密码强加密 bean
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * spring security 过滤链
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                // 禁止使用明文验证
                .httpBasic(AbstractHttpConfigurer::disable)
                // 禁止 CSRF 验证
                .csrf(AbstractHttpConfigurer::disable)
                // 禁止默认登录页面
                .formLogin(AbstractHttpConfigurer::disable)
                // 禁止默认退出页面
                .logout(AbstractHttpConfigurer::disable)
                // 禁止默认Header支持 iframe 访问页面
                .headers(AbstractHttpConfigurer::disable)
                // 禁止使用 session
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                // 设置运行访问的资源
                .authorizeHttpRequests(auth ->
                        auth.requestMatchers(
                                        "/layui/**",
                                        "/login.html",
                                        "/index.html",
                                        "/register.html",
                                        "/api/ai-cloud/v1/captcha/create",
                                        "/api/ai-cloud/v1/user/login",
                                        "/api/ai-cloud/v1/user/register"
                                ).permitAll()
                                // 其他资源访问都需要验证
                                .anyRequest().authenticated()
                )
                .addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
